package cn.fintecher.gis.service;

import cn.fintecher.gis.entity.LandDisaster;
import cn.fintecher.gis.entity.QLandDisaster;
import cn.fintecher.gis.enums.RiskGrand;
import cn.fintecher.gis.enums.SusceptibleGrand;
import cn.fintecher.gis.exception.BadRequestException;
import cn.fintecher.gis.model.request.LandDisasterRequest;
import cn.fintecher.gis.model.response.LandDisasterResponse;
import cn.fintecher.gis.model.session.SessionModel;
import cn.fintecher.gis.respository.DistrictInfoRepository;
import cn.fintecher.gis.respository.LandDisasterRepository;
import cn.fintecher.gis.respository.OperatorRepository;
import cn.fintecher.gis.utils.BeanUtils;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("landDisasterService")
public class LandDisasterService {

    private final Logger logger = LoggerFactory.getLogger(LandDisasterService.class);

    @Autowired
    private LandDisasterRepository landDisasterRepository;

    @Autowired
    private OperatorRepository operatorRepository;

    @Autowired
    private DistrictInfoRepository districtInfoRepository;
    /**
     * 灾地信息维护
     * @param request
     * @param sessionModel
     */
    public void createLandDisaster(LandDisasterRequest request, SessionModel sessionModel) {
        LandDisaster landDisaster = new LandDisaster();
        BeanUtils.copyPropertiesIgnoreNull(request, landDisaster);
        districtInfoRepository.findById(request.getPrefecture()).ifPresent(districtInfo -> {
            landDisaster.setDistrictInfo(districtInfo);
            return;
        });
        landDisaster.setCreateTime(new Date());
        operatorRepository.findById(sessionModel.getId()).ifPresent(operator -> {
            landDisaster.setOperator(operator);
            return;
        });
        landDisasterRepository.save(landDisaster);
    }


    /**
     * 隐患点信息的修改
     *
     * @param request
     */
    public void editLandDisaster(LandDisasterRequest request) {
        LandDisaster landDisaster = landDisasterRepository.findById(request.getId()).orElseThrow(
                () -> new BadRequestException("landDisaster", "landDisaster.is.not.exist"));
        BeanUtils.copyPropertiesIgnoreNull(request, landDisaster);
        districtInfoRepository.findById(request.getPrefecture()).ifPresent(districtInfo -> {
            landDisaster.setDistrictInfo(districtInfo);
            return;
        });
        landDisasterRepository.save(landDisaster);
    }

    /**
     * 灾地信息查询
     * @param pageable
     * @return
     */
    public Page<LandDisasterResponse> queryLandDisasterAll(Pageable pageable, String name, RiskGrand grade, SusceptibleGrand susceptible) {
        BooleanBuilder builder = new BooleanBuilder();
        QLandDisaster qLandDisaster = QLandDisaster.landDisaster;
        if (StringUtils.isNotBlank(name)) {
            builder.and(qLandDisaster.name.contains(name));
        }
        if (Objects.nonNull(grade)) {
            builder.and(qLandDisaster.grade.eq(grade));
        }
        if (Objects.nonNull(susceptible)) {
            builder.and(qLandDisaster.susceptible.eq(susceptible));
        }
        Page<LandDisaster> landDisasterPage = landDisasterRepository.findAll(builder, pageable);
        Page<LandDisasterResponse> page = landDisasterPage.map(landDisaster -> {
            LandDisasterResponse response = new LandDisasterResponse();
            BeanUtils.copyPropertiesIgnoreNull(landDisaster, response);
            response.setUserName(landDisaster.getOperator().getUsername());
            response.setPrefecture(landDisaster.getDistrictInfo().getId());
            response.setPrefectureName(landDisaster.getDistrictInfo().getDistrictName());
            return response;
        });
        return page;
    }

    /**
     * 查询所有隐患点信息
     *
     * @return
     */
    public List<LandDisasterResponse> getLandDisaster(RiskGrand grade) {
        List<LandDisaster> landDisasterList = new ArrayList<>();
        if (Objects.nonNull(grade)) {
            Iterator<LandDisaster> iterator = landDisasterRepository.findAll(QLandDisaster.landDisaster.grade.eq(grade)).iterator();
            landDisasterList.addAll(Lists.newArrayList(iterator));
        } else {
            landDisasterList = landDisasterRepository.findAll();
        }
        List<LandDisasterResponse> list = landDisasterList.stream().map(landDisaster -> {
            LandDisasterResponse response = new LandDisasterResponse();
            BeanUtils.copyPropertiesIgnoreNull(landDisaster, response);
            response.setUserName(landDisaster.getOperator().getUsername());
            response.setPrefecture(landDisaster.getDistrictInfo().getId());
            response.setPrefectureName(landDisaster.getDistrictInfo().getDistrictName());
            return response;
        }).collect(Collectors.toList());
        return list;
    }
}
